import hre from "hardhat";
import fs from "fs";
const { ethers } = hre;

async function main() {
    console.log("🧪 开始简单合约测试...");
    console.log("Debug: hre keys:", Object.keys(hre));
    console.log("Debug: ethers available:", !!hre.ethers);

    try {
        // 获取测试账户
        const [deployer, seller, bidder1, bidder2] = await hre.ethers.getSigners();
        console.log("👥 测试账户:");
        console.log("🏗️  部署者:", deployer.address);
        console.log("💰 卖家:", seller.address);
        console.log("🎯 竞拍者1:", bidder1.address);
        console.log("🎯 竞拍者2:", bidder2.address);

        // ============= 第一步：部署Mock合约测试 =============
        console.log("\n🚀 第一步：部署Mock合约");

        // 1. 部署Mock价格聚合器
        console.log("📊 部署Mock ETH/USD价格聚合器...");
        const MockAggregator = await ethers.getContractFactory("MockV3Aggregator");
        const mockETHUSDFeed = await MockAggregator.deploy(
            8,                                      // 8位小数
            ethers.parseUnits("2000", 8)           // $2000
        );
        await mockETHUSDFeed.waitForDeployment();
        console.log("✅ MockETHUSDFeed 部署成功:", mockETHUSDFeed.target);

        // 测试价格获取
        const priceData = await mockETHUSDFeed.latestRoundData();
        console.log("📈 获取到的价格:", ethers.formatUnits(priceData[1], 8), "USD");

        // 2. 部署Mock ERC721
        console.log("🎨 部署Mock ERC721...");
        const MockERC721 = await ethers.getContractFactory("MockERC721");
        const mockNFT = await MockERC721.deploy("Test NFT", "TNFT");
        await mockNFT.waitForDeployment();
        console.log("✅ MockERC721 部署成功:", mockNFT.target);

        // 铸造测试NFT
        await mockNFT.mint(seller.address, 1);
        const owner = await mockNFT.ownerOf(1);
        console.log("🎨 NFT Token 1 所有者:", owner);

        // 3. 部署Mock CCIP路由器
        console.log("🔗 部署Mock CCIP路由器...");
        const MockCCIPRouter = await ethers.getContractFactory("MockCCIPRouter");
        const mockCCIPRouter = await MockCCIPRouter.deploy();
        await mockCCIPRouter.waitForDeployment();
        console.log("✅ MockCCIPRouter 部署成功:", mockCCIPRouter.target);

        // 4. 部署简单跨链拍卖合约
        console.log("🌉 部署SimpleCrossChainAuction...");
        const SimpleCrossChainAuction = await ethers.getContractFactory("SimpleCrossChainAuction");
        const simpleCrossChainAuction = await SimpleCrossChainAuction.deploy(
            mockCCIPRouter.target
        );
        await simpleCrossChainAuction.waitForDeployment();
        console.log("✅ SimpleCrossChainAuction 部署成功:", simpleCrossChainAuction.target);

        // ============= 第二步：测试跨链拍卖基本功能 =============
        console.log("\n🌉 第二步：测试跨链拍卖功能");

        // 验证合约所有者
        const owner_addr = await simpleCrossChainAuction.owner();
        console.log("👑 跨链拍卖合约所有者:", owner_addr);

        // 添加支持的链
        const ETHEREUM_CHAIN_SELECTOR = 5009297550715157269n;
        const POLYGON_CHAIN_SELECTOR = 4051577828743386545n;

        console.log("🔗 添加支持的链...");
        await simpleCrossChainAuction.addSupportedChain(ETHEREUM_CHAIN_SELECTOR);
        await simpleCrossChainAuction.addSupportedChain(POLYGON_CHAIN_SELECTOR);

        // 验证链支持
        const isEthereumSupported = await simpleCrossChainAuction.isChainSupported(ETHEREUM_CHAIN_SELECTOR);
        const isPolygonSupported = await simpleCrossChainAuction.isChainSupported(POLYGON_CHAIN_SELECTOR);

        console.log("✅ Ethereum链支持:", isEthereumSupported);
        console.log("✅ Polygon链支持:", isPolygonSupported);

        // 初始化跨链拍卖
        console.log("🏺 初始化跨链拍卖...");
        const startPrice = ethers.parseEther("1"); // 1 ETH
        const duration = 3600; // 1小时

        await simpleCrossChainAuction.initializeAuction(
            mockNFT.target,
            1,
            seller.address,
            startPrice,
            duration
        );
        console.log("✅ 跨链拍卖初始化成功!");

        // 获取拍卖信息
        const auctionInfo = await simpleCrossChainAuction.auctionInfo();
        console.log("🏺 拍卖信息:");
        console.log("   NFT合约:", auctionInfo.nftContract);
        console.log("   Token ID:", auctionInfo.tokenId.toString());
        console.log("   卖家:", auctionInfo.seller);
        console.log("   起拍价:", ethers.formatEther(auctionInfo.startPrice), "ETH");
        console.log("   是否活跃:", auctionInfo.isActive);

        // 获取拍卖状态
        const [isActive, isEnded, isSettled, timeRemaining, highestBidAmount] =
            await simpleCrossChainAuction.getAuctionStatus();

        console.log("📊 拍卖状态:");
        console.log("   是否活跃:", isActive);
        console.log("   是否结束:", isEnded);
        console.log("   是否结算:", isSettled);
        console.log("   剩余时间:", timeRemaining.toString(), "秒");
        console.log("   最高出价:", ethers.formatEther(highestBidAmount), "ETH");

        // ============= 第三步：模拟跨链出价 =============
        console.log("\n💰 第三步：模拟跨链出价");

        // 构造CCIP消息
        const bidAmount = ethers.parseEther("2"); // 2 ETH出价

        const messageData = ethers.AbiCoder.defaultAbiCoder().encode(
            ["address", "uint256"],
            [bidder1.address, bidAmount]
        );

        const ccipMessage = {
            messageId: ethers.keccak256("0x1234"),
            sourceChainSelector: ETHEREUM_CHAIN_SELECTOR,
            sender: ethers.AbiCoder.defaultAbiCoder().encode(["address"], [bidder1.address]),
            data: messageData,
            destTokenAmounts: []
        };

        console.log("🌉 模拟接收跨链出价...");
        console.log("   出价者:", bidder1.address);
        console.log("   出价金额:", ethers.formatEther(bidAmount), "ETH");
        console.log("   源链:", ETHEREUM_CHAIN_SELECTOR.toString());

        // 通过Mock路由器发送CCIP消息
        await mockCCIPRouter.simulateCCIPReceive(simpleCrossChainAuction.target, ccipMessage);
        console.log("✅ 跨链出价接收成功!");

        // 检查出价记录
        const bidsCount = await simpleCrossChainAuction.getCrossChainBidsCount();
        console.log("📊 跨链出价数量:", bidsCount.toString());

        // 获取最高出价
        const highestBid = await simpleCrossChainAuction.highestBid();
        console.log("🏆 最高出价信息:");
        console.log("   出价者:", highestBid.bidder);
        console.log("   出价金额:", ethers.formatEther(highestBid.amount), "ETH");
        console.log("   源链:", highestBid.sourceChain.toString());

        // ============= 第四步：测试总结 =============
        console.log("\n" + "=".repeat(80));
        console.log("🎉 简单合约测试完成总结");
        console.log("=".repeat(80));
        console.log("✅ Mock合约部署：成功");
        console.log("✅ 跨链拍卖部署：成功");
        console.log("✅ 链支持管理：成功");
        console.log("✅ 拍卖初始化：成功");
        console.log("✅ 跨链出价：成功");
        console.log("✅ 状态查询：成功");
        console.log("=".repeat(80));

        // 保存测试结果
        const testResults = {
            timestamp: new Date().toISOString(),
            testStatus: "PASSED",
            contracts: {
                MockETHUSDFeed: mockETHUSDFeed.target,
                MockERC721: mockNFT.target,
                MockCCIPRouter: mockCCIPRouter.target,
                SimpleCrossChainAuction: simpleCrossChainAuction.target
            },
            testResults: {
                mockContracts: "✅ 成功",
                crossChainAuction: "✅ 成功",
                chainSupport: "✅ 成功",
                auctionInit: "✅ 成功",
                crossChainBidding: "✅ 成功"
            },
            auctionData: {
                totalBids: bidsCount.toString(),
                highestBidder: highestBid.bidder,
                highestBidETH: ethers.formatEther(highestBid.amount),
                supportedChains: [ETHEREUM_CHAIN_SELECTOR.toString(), POLYGON_CHAIN_SELECTOR.toString()]
            }
        };

        fs.writeFileSync(
            'simple-test-results.json',
            JSON.stringify(testResults, null, 2)
        );
        console.log("\n💾 简单测试结果已保存到 simple-test-results.json");

        // 下一步建议
        console.log("\n📝 下一步测试建议:");
        console.log("1. 测试更多跨链出价");
        console.log("2. 测试拍卖结算");
        console.log("3. 测试权限管理");
        console.log("4. 部署完整的可升级合约版本");

        return testResults;

    } catch (error) {
        console.error("\n❌ 简单测试失败:", error.message);
        console.error("错误详情:", error);

        const failedResults = {
            timestamp: new Date().toISOString(),
            testStatus: "FAILED",
            error: error.message,
            stack: error.stack
        };

        fs.writeFileSync(
            'simple-test-results.json',
            JSON.stringify(failedResults, null, 2)
        );

        process.exit(1);
    }
}

// 直接执行main函数
main()
    .then(() => {
        console.log("\n🎊 简单测试执行完毕!");
        process.exit(0);
    })
    .catch((error) => {
        console.error("❌ 简单测试执行失败:", error);
        process.exit(1);
    });

export { main as runSimpleTest };
